﻿#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif

#include "WebSocketClient.h"
#include <QDebug>
 
WSClient::WSClient(QObject *parent)
    : QObject(parent)
{

}
 
WSClient::~WSClient()
{
    if(nullptr != WSClientObj && WSClientObj->state() == QAbstractSocket::ConnectedState)
    {
        WSClientObj->close();
    }
}

void WSClient::wss_config()
{
    QSslConfiguration conf = WSClientObj->sslConfiguration();
    conf.setPeerVerifyMode(QSslSocket::VerifyNone);
    conf.setProtocol(QSsl::TlsV1_3);
    WSClientObj->setSslConfiguration(conf);
}

//连接服务端
void WSClient::ConnectTo(const QString url)
{
    if(nullptr == WSClientObj)
    {
        WSClientObj = new QWebSocket;   //构造函数未设置参数和指定父对象
        WSClientObj->setParent(this);   //这里必须设置父对象，否则多线程运行报错
        //客户端需要处理的信号：连接成功、断开连接、发生错误、收到消息
        connect(WSClientObj, &QWebSocket::connected, this, &WSClient::on_connected);
        connect(WSClientObj, &QWebSocket::disconnected, this, &WSClient::on_disconnected);
        connect(WSClientObj, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(on_error(QAbstractSocket::SocketError)));
        connect(WSClientObj, &QWebSocket::textMessageReceived, this, &WSClient::NewTextMessage);
        connect(WSClientObj, &QWebSocket::binaryMessageReceived, this, &WSClient::NewBinaryMessage);
    }
    if(url.startsWith("wss"))
    {
        wss_config();
    }
    WSClientObj->open(QUrl(url));
}
//断开连接
void WSClient::Disconnect()
{
    WSClientObj->close();
    WSClientObj->deleteLater();
    WSClientObj = nullptr;
}
 //发消息，字符串
void WSClient::sendTextMessage(const QString& message)
{
    WSClientObj->sendTextMessage(message);
}

 //发消息，二进制
void WSClient::sendBinaryMessage(const QByteArray& data)
{
    WSClientObj->sendBinaryMessage(data);
}
 //连接成功，通知UI
void WSClient::on_connected()
{
    qDebug() << __FILE__ << __LINE__ << "connected";
    emit connection_state("success connected", true);   //true/false用于UI判断更新控件可用状态
}
 //断开连接，通知UI
void WSClient::on_disconnected()
{
    qDebug() << __FILE__ << __LINE__ << "disconnected";
    emit connection_state("success disconnected", false);
}
 //报错，通知UI
void WSClient::on_error(QAbstractSocket::SocketError error)
{
    qDebug() << __FILE__ << __LINE__ << (int)error << WSClientObj->errorString();
    emit occur_error("error message:" + WSClientObj->errorString() + "\nerror code:" + QString::number(error));
}
